package comm.SocketUtil;

import comm.bean.GroupBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ServerSocketBase {

    private static final Logger logger = LoggerFactory.getLogger(ServerSocketBase.class);

    @Autowired
    GroupBean groupBean;

    //public static Socket cilent = null;

    private  Map<String,ServerThread> threadPool = new HashMap<>();

    //客户端连接时：为true  断开时：为false
    //这样处理有个问题，bufferedWriter.write写一次失败之后才会改变客户端连接状态
    //public static boolean isConnend;


    public void ServerSocket() {
        try {
            ServerSocket serverSocket = new ServerSocket(groupBean.Port);//持续监听接口
            logger.info("启动服务器....端口为:" + groupBean.Port + " wait connect...");

            while (true) {
                Socket cilent = serverSocket.accept();//建立socket连接

                logger.info("收到客户端连接，客户端:" + cilent.getInetAddress().getHostAddress()+":端口号"+cilent.getPort() + ",已连接到服务器");
                //isConnend=true;
                ServerThread serverThread = new ServerThread(cilent);
                serverThread.start();
                logger.info("thread start");
                threadPool.put(cilent.getInetAddress().getHostAddress()+":"+cilent.getPort(),serverThread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
